<?php
namespace App\Model;

use App\Think\Db;
use App\Model\Trade;

class Bonus extends BaseModel
{

	protected static $instance;
    // 初始化
    public static function instance(){
        if (is_null(self::$instance)) self::$instance = new static();
        return self::$instance;
    }


    /**
     * 新用户注册送现金:20元
     * @param  string $user_id 用户ID
     */
    public static function register($user_id){
        $inc_money = 20;
        Trade::bonus(['bonus_type'=>__FUNCTION__, 'money'=>$inc_money, 'user_id'=>$user_id, 'memo'=>bonus_name(__FUNCTION__)]);
        //门槛值计算
        $multiple = (int)bonus_name(__FUNCTION__, 'multiple');
        Db::name('stats_user')->where("user_id='{$user_id}'")->setInc("ts_default", $inc_money*$multiple);
        return true;
    }

    /**
     * 首充充值红利
     * @param  string $user_id 用户ID
     * @param  string $money 充值金额
     */
    public static function first_recharge($user_id, $money=0, $plat_type='default'){
    	$user_info = Db::name('user u')->field('ul.*')->join('user_level ul', 'u.level=ul.id', 'LEFT')->where("u.id='{$user_id}'")->find();
    	$inc_money = @$user_info['ac_first_recharge']*$money/100;
        $inc_money = $inc_money > 600 ? 600 : $inc_money;
        Trade::bonus(['bonus_type'=>__FUNCTION__, 'money'=>$inc_money, 'user_id'=>$user_id, 'memo'=>bonus_name(__FUNCTION__)]);
        //门槛值计算
        $multiple = (int)bonus_name(__FUNCTION__, 'multiple');
        Db::name('stats_user')->where("user_id='{$user_id}'")->setInc("ts_".$plat_type, ($money+$inc_money)*$multiple);
        return true;
    }

    /**
     * 二次充值红利
     * @param  string $user_id 用户ID
     * @param  string $money 充值金额
     */
    public static function second_recharge($user_id, $money=0, $plat_type='default'){
    	$user_info = Db::name('user u')->field('ul.*')->join('user_level ul', 'u.level=ul.id', 'LEFT')->where("u.id='{$user_id}'")->find();
    	$inc_money = @$user_info['ac_second_recharge']*$money/100;
        $inc_money = $inc_money > 300 ? 300 : $inc_money;
        Trade::bonus(['bonus_type'=>__FUNCTION__, 'money'=>$inc_money, 'user_id'=>$user_id, 'memo'=>bonus_name(__FUNCTION__)]);
        //门槛值计算
        $multiple = (int)bonus_name(__FUNCTION__, 'multiple');
        Db::name('stats_user')->where("user_id='{$user_id}'")->setInc("ts_".$plat_type, ($money+$inc_money)*$multiple);
        return true;
    }

    /**
     * 银行卡充值红利
     * @param  string $user_id 用户ID
     * @param  string $money 充值金额
     */
    public static function bank_recharge($user_id, $money=0, $order_sn=''){
        $user_info = Db::name('user u')->field('ul.*')->join('user_level ul', 'u.level=ul.id', 'LEFT')->where("u.id='{$user_id}'")->find();
        $inc_money = @$user_info['ac_bank_recharge']*$money/100;
        Trade::bonus(['bonus_type'=>__FUNCTION__, 'money'=>$inc_money, 'user_id'=>$user_id, 'memo'=>bonus_name(__FUNCTION__), 'ext_json'=>['order_sn'=>$order_sn] ]);
        //门槛值计算
        $multiple = (int)bonus_name(__FUNCTION__, 'multiple');
        Db::name('stats_user')->where("user_id='{$user_id}'")->setInc("ts_default", $money+$inc_money*$multiple);
    	return true;
    }

    /**
     * 邀请红利
     * @param  string $invite_user_id 邀请人ID
     * @param  string $reg_user_id    注册用户ID
     */
    public static function invite($invite_user_id=0, $reg_user_id=0){
        if($invite_user_id <= 0) return false;
    	$user_info = Db::name('user u')->field('ul.*')->join('user_level ul', 'u.level=ul.id', 'LEFT')->where("u.id='{$invite_user_id}'")->find();
    	$inc_money = @$user_info['ac_invite'];
        Trade::bonus(['bonus_type'=>'invite', 'money'=>$inc_money, 'user_id'=>$invite_user_id, 'memo'=>bonus_name('invite')]);
        //门槛值计算
        $multiple = (int)bonus_name(__FUNCTION__, 'multiple');
        Db::name('stats_user')->where("user_id='{$invite_user_id}'")->setInc("ts_default", $inc_money*$multiple);
    	return true;
    }
    /**
     * 每月红包红利
     */
    public static function month_crontab(){
        $month_time = for_timestamp('month');
        $arr = $user_list = [];
        $this_month = date('Ym');
        //本月已经领取过的
        $no_userids = Db::name('trade_bonus')->where("bonus_type='month' AND createtime>='{$month_time['start']}' AND createtime<='{$month_time['end']}'")->column('user_id');
        $user_list = Db::name('user u')->field('u.id,u.level,ul.ac_month')->join('user_level ul', 'u.level=ul.id', 'LEFT')->where("u.status='normal'")->select();
        foreach ($user_list as $k => $v) {
            if(in_array($v['id'], $no_userids) || $v['ac_month']==0) continue;//本月注册或红利金额等于0，不能领取
            // $bonus_id = db_get_field('trade_bonus', "user_id='{$v['id']}' AND bonus_type='month' AND ext_json->'$.month'='{$this_month}'", 'id');
            // if($bonus_id>0) continue; //已经领取过，不能领取

            Trade::bonus(['bonus_type'=>'month', 'money'=>$v['ac_month'], 'user_id'=>$v['id'], 'memo'=>bonus_name('month'), 'ext_json'=>['month'=>$this_month] ]);
            //门槛值计算
            $multiple = (int)bonus_name(__FUNCTION__, 'multiple');
            Db::name('stats_user')->where("user_id='{$v['id']}'")->setInc("ts_default", $v['ac_month']*$multiple);

            $arr[$k] = ['user_id'=>$v['id'], 'money'=>$v['ac_month'], 'month'=>date('m')];
        }
        if(!empty($arr)) return $arr;
        return false;
    }

    /**
     * 会员升级红利
     * @param  string $user_id 用户ID
     */
    public static function upgrade($user_id){
        $user_info = Db::name('user u')->field('ul.*')->join('user_level ul', 'u.level=ul.id', 'LEFT')->where("u.id='{$user_id}'")->find();
        //每日仅能升级一次
        $bonus_date = Db::name('trade_bonus')->where("user_id='{$user_id}' AND bonus_type='upgrade'")->order('createtime DESC')->value('createtime');
        if(date('Y-m-d') == date('Y-m-d',$bonus_date)) return false;
        //是否已经领取过该等级奖励
        $level_up = $user_info['id']+1;
        $bonus_id = db_get_field('trade_bonus', "user_id='{$user_id}' AND bonus_type='upgrade' AND ext_json->'$.level'='{$level_up}' ", 'id');
        if($bonus_id>0){
            Db::name('user')->where("id='{$user_id}'")->setInc("level");
            return true;
        } 
        //未领取过
        $inc_money = @$user_info['ac_upgrade'];
        Trade::bonus(['bonus_type'=>'upgrade', 'money'=>$inc_money, 'user_id'=>$user_id, 'memo'=>bonus_name('upgrade')]);
        //门槛值计算
        $multiple = (int)bonus_name(__FUNCTION__, 'multiple');
        Db::name('stats_user')->where("user_id='{$user_id}'")->setInc("ts_default", $inc_money*$multiple);
        //升级成功
        Db::name('user')->where("id='{$user_id}'")->setInc("level");
        return true;
    }

    /**
     * 生日礼金红利
     * @param  string $user_id 用户ID
     */
    public static function birth($user_id){
    	$year_time = for_timestamp('year');
    	// $id = Db::name('trade_bonus')->where("bonus_type='birth' AND user_id='{$user_id}' AND createtime>='{$year_time['start']}' AND createtime<='{$year_time['end']}'")->value('id');
    	// if($id > 0) return false;
    	$user_info = Db::name('user u')->field('u.birthday,u.jointime,ul.*')->join('user_level ul', 'u.level=ul.id', 'LEFT')->where("u.id='{$user_id}'")->find();
        // if( (time()-$user_info['jointime'])<86400*90 ) return false;
    	// if(date('m-d',time()) != date("m-d",strtotime("{$user_info['birthday']} 00:00:00"))) return false;
        $inc_money = $user_info['ac_birth'];
        Trade::bonus(['bonus_type'=>'birth', 'money'=>$inc_money, 'user_id'=>$user_id, 'memo'=>bonus_name('birth'), 'ext_json'=>['year'=>date('Y')] ]);
        //门槛值计算
        $multiple = (int)bonus_name(__FUNCTION__, 'multiple');
        Db::name('stats_user')->where("user_id='{$user_id}'")->setInc("ts_default", $inc_money*$multiple);
    	return true;
    }

    /**
     * 返水红利
     * @param  string $user_id 用户ID
     * @param  string $money 注单金额
     */
    public static function rebate($user_id, $moeny){
        $arr = [
            'type'       => 'rebate',
            'user_id'    => $param['user_id'],
            'money'      => $param['money'],
            'level_id'   => $param['level_id'],
            'ext_json'   => $param['ext_json'],
            'createtime' => time()
        ];
        $sql = "INSERT INTO fa_trade_bonus(type, user_id, money, level_id, ext_json, createtime) ".
             "SELECT '{$arr['type']}', '{$arr['user_id']}','{$arr['money']}','{$arr['level_id']}','{$arr['ext_json']}','{$arr['createtime']}' ".
             "FROM DUAL WHERE NOT EXISTS(SELECT type,user_id,ext_json FROM fa_trade_bonus WHERE user_id='{$arr['user_id']}' AND type= 'rebate' AND ext_json='{$arr['ext_json']}')";
        if(Db::execute(Db::parseSqlTable($sql))) return true;
        return false;
    }

    /**
     * 返水红利[后台任务]
     * @param  string $day 日期
     */
    public static function rebate_crontab($day){
        $day = date('Y-m-d', strtotime($day));
        $res = Db::name('stats_user_day')->field('id,user_id,total_rebate')->where("day='{$day}' AND rebate_status=0")->select();
        $arr = [];

        foreach ($res as $k => $v) {
            $inc_money = $v['total_rebate'];
            $user_id   = $v['user_id'];
            Db::name('stats_user_day')->where("id='{$v['id']}'")->update(['rebate_status'=>1]);
            if($inc_money <= 0) continue;
            Db::name('user')->where("id='{$user_id}'")->update(['money'=>Db::raw("money+{$inc_money}")]);
            //门槛值计算
            $multiple = (int)bonus_name('rebate');
            Db::name('stats_user')->where("user_id='{$user_id}'")->setInc("ts_default", $inc_money*$multiple);
            Trade::bonus(['bonus_type'=>'rebate', 'money'=>$inc_money, 'user_id'=>$user_id, 'memo'=>bonus_name('rebate')]);
            $arr[$k] = ['day'=>$day, 'user_id'=>$user_id, 'rebate_money'=>$inc_money];
            // $output->writeln("Rebate /// day:{$day},user_id:{$v['user_id']},total_rebate:{$inc_money}");
        }
        if(!empty($arr)) return $arr;
        return false;
    }


}
